<template>
  <el-dialog
    top="30px"
    width="900px"
    append-to-body
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :model="formData" v-loading="loading" :rules="rules" ref="form" label-width="120px">
      <el-form-item label="小组名称" prop="group_name">
        <el-input
          v-model="formData.group_name"
          placeholder="请输入小组名称"
          class="form-control-ml"
        ></el-input>
      </el-form-item>
      <el-form-item label="小组区域" prop="address_code_str">
        <select-area
          v-model="formData.address_code_str"
          @change="setAddressName"
          placeholder="请选择小组区域"
          class="form-control-ml"
        ></select-area>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="formData.remark" placeholder="备注" class="form-control-ml"></el-input>
      </el-form-item>
      <el-form-item>
        <table class="table table-bordered table-sm vertical-align-middle text-center">
          <tr>
            <td width="20%">区域</td>
            <td width="20%">A角</td>
            <td width="20%">B角</td>
            <td width="20%">风控员</td>
            <td width="20%">财务经办人</td>
          </tr>
          <tr v-if="!addressArray.length">
            <td colspan="4" class="text-muted">请先选择小组区域</td>
          </tr>
          <tr v-for="(p, index) of addressArray" :key="index">
            <td>{{ p.address_code_name }}</td>
            <td class="input-td">
              <select-staff
                v-model="p.res_a"
                @select="staff => selectA(staff, p)"
                placeholder="请选择A角"
              ></select-staff>
            </td>
            <td class="input-td">
              <select-staff
                v-model="p.res_b"
                @select="staff => selectB(staff, p)"
                placeholder="请选择B角"
              ></select-staff>
            </td>
            <td class="input-td">
              <select-staff
                v-model="p.risk_person"
                @select="staff => (p.risk_person_name = staff.realName || '')"
                :includeJob="['org_r_emp', 'org_r_manage', 'org_dg_risk_manage']"
                placeholder="请选择风控员"
              ></select-staff>
            </td>
            <td class="input-td">
              <select-staff
                v-model="p.finance_person"
                @select="staff => (p.finance_person_name = staff.realName || '')"
                :includeJob="['org_dg_finance_manage', 'org_f_manage', 'org_f_emp']"
                placeholder="请选择财务经办人"
              ></select-staff>
            </td>
          </tr>
        </table>
      </el-form-item>
    </el-form>
    <div class="text-center pt-2">
      <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
        保存
      </el-button>
      <el-button class="btn-long" @click="onClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import SelectArea from '@/credit/components/select/SelectArea'
import SelectStaff from '@/components/select/SelectStaff'
import { mapGetters } from 'vuex'
export default {
  components: {
    SelectArea,
    SelectStaff,
  },
  props: {
    visible: Boolean,
    tableId: String,
  },
  data() {
    return {
      loading: false,
      submitLoading: false,
      tableName: 'bus_group',
      tableData: {
        group_name: '',
        address_code_str: '',
      },
      detailData: [],
      formData: {
        group_name: '',
        address_code_str: '',
      },
      rules: {
        group_name: { required: true, message: '请输入小组名称', trigger: 'blur' },
        address_code_str: { required: true, message: '请选择适用区域', trigger: 'change' },
      },
      addressArray: [],
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  watch: {
    tableId() {
      this.getData()
    },
    visible(value) {
      if (value) {
        this.setData()
      }
    },
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      if (!this.tableId) {
        return
      }
      const params = {
        subKey: 'bus_group_detail.bus_group_id',
        bus_group_id: this.tableId,
      }
      this.tableData.group_name = ''
      this.tableData.address_code_str = ''
      this.tableData.bus_group_id = this.tableId
      this.detailData = []
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, params)
        .then(res => {
          const data = (res && res.data && res.data[0]) || {}
          this.tableData.address_code_str = data.address_code_str || ''
          this.tableData.group_name = data.group_name || ''
          if (data.bus_group_detail && data.bus_group_detail.length) {
            data.bus_group_detail
              .sort((a, b) => a.order_num - b.order_num)
              .forEach(detail => {
                this.detailData.push({
                  order_num: detail.order_num,
                  bus_group_id: this.tableId,
                  res_a: detail.res_a,
                  res_b: detail.res_b,
                  risk_person: detail.risk_person,
                  address_code: detail.address_code,
                  address_code_name: detail.address_code_name,
                  id: detail.id,
                })
              })
          }
        })
        .finally(() => {
          this.setData()
          this.loading = false
        })
    },
    setData() {
      this.formData = { ...this.tableData }
      this.addressArray = this.detailData.map(item => item)
    },
    selectA(staff, p) {
      p.res_a_name = staff.realName || ''
      p.res_a_phone = staff.phoneNumber || ''
    },
    selectB(staff, p) {
      p.res_b_name = staff.realName || ''
      p.res_b_phone = staff.phoneNumber || ''
    },
    submit() {
      this.$refs.form
        .validate()
        .then(() => {
          this.saveData()
        })
        .catch(() => {
          this.$message.error('输入有误，重新输入')
        })
    },
    saveData() {
      this.formData.service_id = this.clientId
      for (let p of this.addressArray) {
        if (!p.res_a) {
          return this.$message.warning(`请选择${p.address_code_name}的项目A角`)
        }
        if (!p.res_b) {
          return this.$message.warning(`请选择${p.address_code_name}的项目B角`)
        }
        if (!p.risk_person) {
          return this.$message.warning(`请选择${p.address_code_name}的风控员`)
        }
      }
      if (this.formData.bus_group_id) {
        this.putData()
      } else {
        this.postData()
      }
    },
    putData() {
      const formData = {
        masterTableInfo: JSON.stringify(this.formData),
        masterTableName: 'bus_group',
        slaveTableInfo: JSON.stringify(this.addressArray),
        slaveTableName: 'bus_group_detail',
      }
      this.submitLoading = true
      this.$api
        .relatedUpdate(this.$serviceName, formData)
        .then(() => {
          this.$message.success('保存成功')
          this.$emit('success', true)
          this.onClose()
        })
        .catch(() => {
          this.$message.error('保存失败')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    postData() {
      const formData = {
        masterTableInfo: JSON.stringify(this.formData),
        masterTableName: 'bus_group',
        slaveTableInfo: JSON.stringify(this.addressArray),
        slaveTableName: 'bus_group_detail',
      }
      this.submitLoading = true
      this.$api
        .relatedBatch(this.$serviceName, formData)
        .then(() => {
          this.$message.success('保存成功')
          this.$emit('success', true)
          this.onClose()
        })
        .catch(() => {
          this.$message.error('保存失败，请重试！！')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    setAddressName(value, name) {
      this.addressArray = (name || []).map((it, index) => {
        const item = this.addressArray.find(item => item.address_code === it.id)
        if (item) {
          item.order_num = index + 1
          return item
        } else {
          return {
            address_code_name: it.geo_name,
            address_code: it.id,
            order_num: index + 1,
          }
        }
      })
    },
    onClose() {
      this.formData.group_name = ''
      this.formData.address_code_str = ''
      this.addressArray = []
      this.beforeClose()
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.input-td {
  background-color: #ffffee;
}
</style>
